<template>
  <draggable
    v-model="dataSource"
    item-key="id"
    :component-data="{
      tag: 'ul',
      type: 'transition-group',
    }"
    class="min-h-[20px] flex flex-wrap gap-1"
  >
    <template #item="{ element, index }">
      <li
        class="text-white rounded-md w-140px h-44px flex justify-center items-center list-group-item"
        :class="[
          'bg-green-400',
          {
            'bg-gray-300': !element.enabled && currentRecord?.id != element.id,
            'bg-orange-300': currentRecord?.id === element.id,
          },
        ]"
        @click="handleClick(element, index)"
        @dblclick="handleDblclick(element, index)"
      >
        {{ element.name }}
      </li>
    </template>
  </draggable>
  <CommonDrawer @register="registerDrawer" @success="handleSuccess" />
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, h, nextTick, watch } from 'vue';
  import draggable from 'vuedraggable';
  import { useDrawer } from '/@/components/Drawer';
  import CommonDrawer from './CommonDrawer.vue';
  import { isEmpty } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import {
    getVisualGetEditPageSetup,
    getVisualUpdateEditPageSetup,
    getVisualGetShowPageSetup,
    getVisualUpdateShowPageSetup,
  } from '/@/api/module/module';

  export default defineComponent({
    name: 'PageComponentCommon',
    components: { CommonDrawer, draggable },
    props: {
      type: {
        type: String,
        default: '1', //1是编辑 2是详情
      },
      moduleCode: {
        type: String,
        default: '',
      },
      formCode: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      const { createMessage, createConfirm } = useMessage();

      const [registerDrawer, { openDrawer }] = useDrawer();
      const currentRecord = ref<Recordable>({});
      const currentIndex = ref(-1);
      const dataSource = ref<Recordable[]>([]);
      const isReloadAfterUpdate = ref(true);
      const isTabStyleHor = ref(true);
      const reload = async () => {
        try {
          let fetch: any;
          if (props.type == '1') {
            fetch = getVisualGetEditPageSetup;
          } else if (props.type == '2') {
            fetch = getVisualGetShowPageSetup;
          }
          const {
            btnProps,
            isReloadAfterUpdate: _isReloadAfterUpdate,
            isTabStyleHor: _isTabStyleHor,
          } = (await fetch({
            moduleCode: props.moduleCode,
          })) || {};
          dataSource.value = btnProps || [];
          // if (dataSource.value.length == 0) {
          //   const obj = {
          //     cond: '',
          //     enabled: true,
          //     event: 'link',
          //     href: '',
          //     id: '1',
          //     moduleCode: props.moduleCode,
          //     name: '打印',
          //     params: '',
          //     title: '',
          //   };
          //   if (props.type == '2') {
          //     dataSource.value.push(obj);
          //     const newObj = cloneDeep(obj);
          //     newObj.name = '编辑';
          //     newObj.id = '2';
          //     dataSource.value.push(newObj);
          //   }
          // }
          isReloadAfterUpdate.value = _isReloadAfterUpdate;
          isTabStyleHor.value = _isTabStyleHor;
          console.log('dataSource', dataSource.value);
        } catch (error) {
          console.error('error', error);
        }
      };
      watch(
        () => props.moduleCode,
        async (newVal) => {
          await nextTick();
          if (newVal) {
            await reload();
          }
        },
        {
          immediate: true,
        },
      );
      const handleClick = (record, index) => {
        currentRecord.value = record;
        currentIndex.value = index;
      };
      const handleDblclick = (record, index) => {
        handleClick(record, index);
        handleEdit();
      };

      function handleCreate() {
        currentIndex.value = -1;
        currentRecord.value = {};
        openDrawer(true, {
          isUpdate: false,
          moduleCode: props.moduleCode,
          formCode: props.formCode,
        });
      }

      function handleEdit() {
        if (isEmpty(currentRecord.value)) {
          createMessage.warning('请选择按钮');
          return;
        }
        openDrawer(true, {
          record: currentRecord.value,
          isUpdate: true,
          moduleCode: props.moduleCode,
          formCode: props.formCode,
        });
      }

      async function handleDelete() {
        if (isEmpty(currentRecord.value)) {
          createMessage.warning('请选择按钮');
          return;
        }

        console.log('handleDeletecurrentRecord', currentRecord.value);

        if (
          currentRecord.value['id'] &&
          (currentRecord.value['id'] == 'btnPrint' || currentRecord.value['id'] == 'btnEdit')
        ) {
          createMessage.warning('系统按钮不能被删除');
          return;
        }

        createConfirm({
          iconType: 'warning',
          title: () => h('span', '确定删除吗？'),
          onOk: async () => {
            dataSource.value.splice(currentIndex.value, 1);
            reset();
          },
        });
      }

      function reset() {
        currentIndex.value = -1;
        currentRecord.value = {};
      }
      function handleSuccess(record: Recordable) {
        if (currentIndex.value < 0) {
          dataSource.value.push(record);
        } else {
          dataSource.value[currentIndex.value] = record;
        }
        reset();
      }

      onMounted(() => {});

      const handleOk = async () => {
        try {
          const record = {
            isReloadAfterUpdate: isReloadAfterUpdate.value,
            isTabStyleHor: isTabStyleHor.value,
            moduleCode: props.moduleCode,
            btnProps: JSON.stringify(dataSource.value),
          };
          console.log('handleOk', record);
          if (props.type == '1') {
            await getVisualUpdateEditPageSetup(record);
          } else if (props.type == '2') {
            await getVisualUpdateShowPageSetup(record);
          }
          createMessage.success('操作成功');
        } catch (error) {}
      };
      return {
        registerDrawer,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        dataSource,
        handleClick,
        currentRecord,
        handleOk,
        handleDblclick,
      };
    },
  });
</script>

<style scoped>
  /* .list-group {
    min-height: 20px;
  } */

  .list-group-item {
    cursor: move;
  }
  /* .list-group-item i {
    cursor: pointer;
  } */
</style>
